package com.cl.code.database.mybatis.module.result;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class ListResultWrapper<Entity> {

    private final List<Entity> list;

    private ListResultWrapper(List<Entity> list) {
        this.list = list;
    }

    public static <Entity> ListResultWrapper<Entity> of(List<Entity> list) {
        return new ListResultWrapper<>(list == null ? Collections.emptyList() : list);
    }

    public List<Entity> result() {
        return list;
    }

    public <R> List<R> result(Function<Entity, R> function) {
        return list.stream().map(function).collect(Collectors.toList());
    }

    public <R> List<R> resultBatch(Function<List<Entity>, List<R>> function) {
        return function.apply(list);
    }

    public <K> Map<K, Entity> resultMap(Function<? super Entity, ? extends K> keyMapper) {
        return resultMap(keyMapper, Function.identity());
    }

    public <K, V> Map<K, V> resultMap(Function<? super Entity, ? extends K> keyMapper, Function<? super Entity, V> valueMapper) {
        return list.stream().collect(Collectors.toMap(keyMapper, valueMapper, (k1, k2) -> k1, LinkedHashMap::new));
    }

    public Stream<Entity> stream() {
        return list.stream();
    }

}
